package com.woyao;

import android.content.Context;
import android.support.v7.widget.CardView;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class SwipeableCardView extends CardView {

    private float startX, startY;
    private OnSwipeListener onSwipeListener;
    private static final int SWIPE_THRESHOLD = 90; // 滑动阈值，单位是像素

    public SwipeableCardView(Context context) {
        super(context);
    }

    public SwipeableCardView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SwipeableCardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = event.getX();
                startY = event.getY();
                return true;

            case MotionEvent.ACTION_UP:
                float endX = event.getX();
                float endY = event.getY();
                float deltaX = endX - startX;
                float deltaY = endY - startY;

                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    // 水平滑动
                    if (Math.abs(deltaX) > SWIPE_THRESHOLD) { // 判断是否超过阈值
                        if (deltaX > 0) {
                            if (onSwipeListener != null) {
                                onSwipeListener.onSwipeRight();
                            }
                        } else {
                            if (onSwipeListener != null) {
                                onSwipeListener.onSwipeLeft();
                            }
                        }
                    }
                } else {
                    // 垂直滑动
                    if (Math.abs(deltaY) > SWIPE_THRESHOLD) { // 判断是否超过阈值
                        if (deltaY > 0) {
                            if (onSwipeListener != null) {
                                onSwipeListener.onSwipeDown();
                            }
                        } else {
                            if (onSwipeListener != null) {
                                onSwipeListener.onSwipeUp();
                            }
                        }
                    }
                }
                return true;
        }
        return super.onTouchEvent(event);
    }

    public void setOnSwipeListener(OnSwipeListener listener) {
        this.onSwipeListener = listener;
    }

    public interface OnSwipeListener {
        void onSwipeLeft();
        void onSwipeRight();
        void onSwipeUp();
        void onSwipeDown();
    }
}